package com.jackie.trpc.config;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.exporter.prometheus.PrometheusHttpServer;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenTelemetryConfig {
    // 定义属性键
    private static final AttributeKey<String> SERVICE_NAME = AttributeKey.stringKey("service.name");
    private static final AttributeKey<String> SERVICE_VERSION = AttributeKey.stringKey("service.version");
    // Span属性键
    public static final AttributeKey<String> TRPC_SERVICE = AttributeKey.stringKey("trpc.service");
    public static final AttributeKey<String> TRPC_METHOD = AttributeKey.stringKey("trpc.method");
    public static final AttributeKey<Long> TRPC_RESPONSE_SIZE = AttributeKey.longKey("trpc.response_size");
    @Value("${opentelemetry.addr}")
    public String opentelemetryAddr;
    @Value("${promethues.ip}")
    public String prome_IP;
    @Value("${promethues.port}")
    public int prome_PORT;
    @Bean
    public OpenTelemetry openTelemetry() {
        
        // 创建资源
        Resource resource = Resource.getDefault()
                .merge(Resource.create(
                        Attributes.of(
                                SERVICE_NAME, "equipment.DataService",
                                SERVICE_VERSION, "1.0.0"
                        )
                ));

        // 配置OTLP trace exporter
        OtlpGrpcSpanExporter spanExporter = OtlpGrpcSpanExporter.builder()
                .setEndpoint(opentelemetryAddr)
                .build();

        // 构建SdkTracerProvider
        SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
                .addSpanProcessor(BatchSpanProcessor.builder(spanExporter).build())
                .setResource(resource)
                .build();

        // 配置Prometheus metrics exporter
        PrometheusHttpServer prometheusExporter = PrometheusHttpServer.builder()
                .setHost(prome_IP)
                .setPort(prome_PORT)  // Prometheus默认抓取端口
                .build();

        // 构建SdkMeterProvider
        SdkMeterProvider meterProvider = SdkMeterProvider.builder()
                .setResource(resource)
                .registerMetricReader(prometheusExporter)
                .build();

        // 创建OpenTelemetry实例
        OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder()
                .setTracerProvider(tracerProvider)
                .setMeterProvider(meterProvider)
                .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
                .buildAndRegisterGlobal();

        // 注册关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            tracerProvider.close();
            meterProvider.close();
        }));

        return openTelemetry;
    }

    @Bean
    public Tracer tracer(OpenTelemetry openTelemetry) {
        return openTelemetry.getTracer("equipment.DataService", "1.0.0");
    }

    @Bean
    public Meter meter(OpenTelemetry openTelemetry) {
        return openTelemetry.getMeter("equipment.DataService.meter");
    }
}